﻿using MRSite.Cache;
using ServiceStack.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MRSite.RedisCache
{
    public class ShanYuRedisCache : BaseCache
    {
        public ShanYuRedisCache(string name,
            IRedisSerializer redisSerializer)
            : base(name)
        {
            _serializer = redisSerializer;
        }


        public override void Clear()
        {
            ShanYuRedisString.Clear();
        }

        public override object GetOrDefault(string key)
        {
            var value = ShanYuRedisString.Get(GetGenerateKey(key));
            return string.IsNullOrWhiteSpace(value) ? null : _serializer.Deserialize(value);
        }

        public override void Remove(string key)
        {
            ShanYuRedisString.Remove(GetGenerateKey(key));
        }

        public override void Set(string key, object value, TimeSpan? slidingExpireTime = null, TimeSpan? absoluteExpireTime = null)
        {
            if (value == null)
            {
                return;
            }
            var type = value.GetType();

            ShanYuRedisString.Set(GetGenerateKey(key), _serializer.Serialize(value, type));
        }

        protected virtual string GetGenerateKey(string key)
        {
            return Name + ",id:" + key;
        }

        private readonly IRedisSerializer _serializer;
    }
}
